package com.mine.site.dao;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import com.mine.site.model.Message;
import com.mine.site.util.DbUtil;

public class MessageDao {
		
	public List<Message> findAll() {
		List<Message> liuyan = new ArrayList<Message>();
		String sql = "select * from message order by createtime desc ";
		Statement stmt = null;
		try {
			stmt = DbUtil.getInstance().getConn().createStatement();
			ResultSet rs = stmt.executeQuery(sql);
			while (rs.next()) {
				Message u = new Message();
				u.setName(rs.getString(1));
				u.setMessage(rs.getString(2));
				u.setCreateTime(rs.getDate(3));
				u.setId(rs.getString(4));
				liuyan.add(u);
			}
			rs.close();
			stmt.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return liuyan;
	}
	
	
	public void update(Message u){
		String sql_update = "update message set message=?,  where id=?";
		PreparedStatement pst = null;
		try {
			pst = DbUtil.getInstance().getConn().prepareStatement(sql_update);
			pst.setString(1, u.getMessage());
			pst.setString(2, u.getName());

			
			pst.executeUpdate();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			try {
				pst.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	public void save(Message u){
		String sql="insert into message values(?,?,?,?)";
		PreparedStatement pst = null;
		try {
			pst = DbUtil.getInstance().getConn().prepareStatement(sql);
			pst.setString(1, u.getName());
			pst.setString(2, u.getMessage());
			
			pst.setTimestamp(3,new java.sql.Timestamp(System.currentTimeMillis()));
			pst.setString(4, u.getId());
			pst.executeUpdate();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			try {
				pst.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	public void delete(String Id){
		String sql = "delete from message where id=?";
		PreparedStatement pst = null;
		try {
			pst = DbUtil.getInstance().getConn().prepareStatement(sql);
			pst.setString(1, Id);
			
			pst.executeUpdate();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			try {
				pst.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
}
